package com.redrose.videodemo.utils;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

/**
 * Desc:音频录制工具类
 *
 * @Author: RedRose
 * Date: 2019/4/15 0015
 * Email: yinsxi@163.com
 */
public class AudioRecordUtil {
    /**
     * 音频信号来源  设置为麦克风
     */
    public static final int AUDIORE_SOURCE = MediaRecorder.AudioSource.MIC;
    /**
     * 设置采样率为44100，目前为常用的采样率，官方文档表示这个值可以兼容所有的设置
     */
    public final static int AUDIO_SAMPLE_RATE = 44100;

    /**
     * 设置声道声道数量为双声道
     */
    public final static int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_STEREO;

    /**
     * 设置采样精度，将采样的数据以PCM进行编码，每次采集的数据位宽为16bit。
     */
    public final static int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    /**
     * 声明recoordBufffer的大小字段
     */
    private int mRecordBufSize = 0;
    /**
     * 工具类工具类实例
     */
    private static AudioRecordUtil mInstance;
    private static final Object O = new Object();
    /**
     * AudioRecord 实例
     */
    private AudioRecord mAudioRecord;
    private boolean isRecording = false;

    private AudioRecordUtil() {
    }

    /**
     * 获取音频工具类实例
     */
    public static AudioRecordUtil getInstance() {
        if (mInstance == null) {
            synchronized (O) {
                if (mInstance == null) {
                    mInstance = new AudioRecordUtil();
                }
            }
        }
        return mInstance;
    }

    public AudioRecord getAudioRecord(int recordBufSize) {
        this.mRecordBufSize = recordBufSize;
        if (mAudioRecord == null) {
            mAudioRecord = new AudioRecord(AUDIORE_SOURCE, AUDIO_SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, mRecordBufSize);
        }
        return mAudioRecord;
    }

    public void releaseAudioRecord() {
        if (mAudioRecord == null) {
            throw new NullPointerException("AudioRecord not be init");
        }
        isRecording = false;
        mAudioRecord.stop();
        mAudioRecord.release();
        mAudioRecord = null;
    }

    public int getmRecordBufSize() {
        return mRecordBufSize;
    }

    /**
     * 设置录音状态
     */
    public void setRecordStatues(boolean recordStatue) {
        this.isRecording = recordStatue;
    }

    /**
     * 获取录音状态
     */
    public boolean isRecording() {
        return isRecording;
    }

}
